package com.pkk.penguin.frame.know.boot.apis.zhiyi;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import com.pkk.penguin.frame.know.boot.constand.ConfigConstand.RequestType;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

/**
 * @description: 同步api
 * @author: peikunkun
 * @create: 2020-05-20 18:00
 **/
@Slf4j
public class SynchApi {


  /**
   * 基础请求接口
   */
  private String baseUrl;

  /**
   * sessionId
   */
  private String sessionId;


  /**
   * 授权用户
   */
  private String authUser;
  /**
   * 授权密码
   */
  public String authPwd;


  public SynchApi(String baseUrl, String authUser, String authPwd) {
    this.baseUrl = baseUrl;
    this.authUser = authUser;
    this.authPwd = authPwd;
  }


  /**
   * @author peikunkun<br>
   * @version V1.0<br>
   * @Title: <br>
   * @Description: <><br>
   * @date 2020/5/20 0020 下午 6:13<br>
   * @URL:[]
   */
  @Getter
  @AllArgsConstructor
  public enum ZhiyiUrl {

    /**
     * 登录
     */
    LOGIN("admin/login.do"),
    /**
     * 保持会话
     */
    KEEPSESSION("admin/keepSession.ohtml"),

    /**
     * 同步缓存数据
     */
    SYNCHCACHE("admin/synchCache.do"),
    ;

    private String url;

  }


  /**
   * @Description: 用户登录
   * @Param: user
   * @Param pwd
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 6:25
   */
  public SynchApi login() {
    try {
      if (StringUtils.isBlank(this.authUser)) {
        throw new IllegalAccessException("PLEASE SPECIL ZHIYI AUTH USER!");
      }
      if (StringUtils.isBlank(this.authPwd)) {
        throw new IllegalAccessException("PLEASE SPECIL ZHIYI AUTH PWD!");
      }
      String loginUrl = baseUrl.concat(ZhiyiUrl.LOGIN.getUrl());
      final HttpRequest post = HttpUtil.createRequest(Method.POST, loginUrl);
      final HashMap<String, Object> param = new HashMap<>();
      param.put("passNo", this.authUser);
      param.put("passPwd", this.authPwd);
      final HttpResponse execute = post.form(param).execute();
      final String body = execute.body();
      if (StringUtils.isBlank(body)) {
        throw new RuntimeException("Authentication failed!->[Authentication Body NULL]");
      }

      //{"result":"1","mes":"登录成功"}
      final JSONObject resultJson = JSONObject.parseObject(body);
      if ("1".equals(resultJson.getString("result"))) {
        final List<HttpCookie> jsessionid = execute.getCookies();
        //"JSESSIONID"
        this.sessionId = jsessionid.get(jsessionid.size() - 1).getValue();
        return this;
      }
      throw new RuntimeException("Authentication failed!->[Authentication Staus Is Not Success]");
    } catch (Exception e) {
      log.info("【之易同步服务】-用户登录-[{}]-出现异常", baseUrl, e);
      throw new RuntimeException("Authentication failed!->[Authentication Exception:" + e.getMessage() + "]");
    }
  }


  /**
   * @Description: 保持会话
   * @return: boolean
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 6:33
   */
  public boolean keepSession() {
    try {
      String keepSessionUrl = baseUrl.concat(ZhiyiUrl.KEEPSESSION.getUrl());
      final HttpRequest get = HttpUtil.createRequest(Method.GET, keepSessionUrl);
      final HashMap<String, Object> param = new HashMap<>();
      param.put("_", System.currentTimeMillis());

      final HashMap<String, String> header = new HashMap<>();
      header.put("Cookie", "JSESSIONID=".concat(sessionId));
      final HttpResponse execute = get.form(param).addHeaders(header).execute();
      final String body = execute.body();
      if (StringUtils.isBlank(body)) {
        return false;
      }

      //{"result":"1","mes":"登录成功"}
      final JSONObject resultJson = JSONObject.parseObject(body);
      if ("1".equals(resultJson.getString("result"))) {
        return true;
      }
      return false;
    } catch (Exception e) {
      return false;
    }
  }


  /**
   * @Description: 建立连接
   * @Param: url
   * @Param type
   * @Param param
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 9:19
   */
  public String connection(String url, RequestType type, String param) throws IllegalAccessException {
    String result = "";
    switch (type) {
      case GET:
        final String requestUrl = baseUrl.concat(url).concat("?").concat(param);
        final HttpRequest get = HttpUtil.createRequest(Method.GET, requestUrl).addHeaders(addSessionHeader());
        final HttpResponse getExec = get.execute();
        result += "[状态:" + getExec.getStatus() + "]";
        result += getExec.body();
        break;
      case POST:
        String[] paramArray = {};
        if (org.apache.commons.lang3.StringUtils.isNotBlank(param)) {
          paramArray = param.split("&");
        }

        //参数解析
        Map<String, Object> paramMap = new HashMap<>();
        for (int i = 0; i < paramArray.length; i++) {
          final String paramStr = paramArray[i];
          final String[] split = paramStr.split("=");
          paramMap.put(split[0], split[1]);
        }
        url = baseUrl.concat(url);
        final HttpRequest post = HttpUtil.createPost(url).addHeaders(addSessionHeader()).form(paramMap);

        final HttpResponse postExec = post.execute();
        result += "[状态:" + postExec.getStatus() + "]";
        result += postExec.body();
        break;
      default:
        throw new IllegalAccessException("不支持的请求方式");
    }
    return result;
  }


  /**
   * @Description: 保持会话
   * @return: boolean
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 6:33
   */
  public String synchCache(String command) {
    try {
      String synchCacheUrl = baseUrl.concat(ZhiyiUrl.SYNCHCACHE.getUrl());
      final HttpRequest get = HttpUtil.createRequest(Method.POST, synchCacheUrl);
      final HashMap<String, Object> param = new HashMap<>();
      param.put("_", System.currentTimeMillis());
      param.put("command", command);

      final HashMap<String, String> header = new HashMap<>();
      header.put("Cookie", "JSESSIONID=".concat(sessionId));
      final HttpResponse execute = get.form(param).addHeaders(header).execute();
      String body = "[状态:" + execute.getStatus() + "]";
      body += execute.body();
      return body;
    } catch (Exception e) {
      return "调用异常:" + e.getMessage();
    }
  }


  /**
   * @Description: 添加header
   * @return: java.util.HashMap<java.lang.String, java.lang.String>
   * @Author: peikunkun
   * @Date: 2020/5/20 0020 下午 9:24
   */
  public HashMap<String, String> addSessionHeader() {
    final HashMap<String, String> header = new HashMap<>();
    header.put("Cookie", "JSESSIONID=".concat(sessionId));
    return header;
  }


}
